<template>
	<view class="news-detail-page">
		<!-- 顶部返回栏 -->
		<view class="top-nav">
			<uni-icons type="back" size="28" color="#333" @click="navigateBack"></uni-icons>
			<view class="empty-box"></view>
		</view>
		<!-- 新闻核心内容区 -->
		<scroll-view class="detail-scroll" scroll-y>
			<view class="detail-container">
				<!-- 新闻标题 -->
				<view class="news-title">{{ newsItem.title }}</view>

				<!-- 作者及发布信息（含头像+关注） -->
				<view class="author-bar">
					<view class="author-info">
						<view class="author-avatar-wrap" @click="viewAuthorHome">
							<image class="author-avatar"
								:src="newsItem.authorAvatar || '/static/avatar/default_author.jpg'" mode="aspectFill">
							</image>
						</view>
						<view class="author-text">
							<text class="author-name">{{ newsItem.author }}</text>
							<text class="publish-time">{{ formatFullTime(newsItem.time) }}</text>
						</view>
					</view>
					<view class="follow-btn" :class="{ 'followed': isFollowed }" @click="toggleFollow">
						<text class="follow-text">{{ isFollowed ? '已关注' : '+关注' }}</text>
					</view>
					<view class="like-share">
						<view class="like-btn" @click="toggleLike">
							<uni-icons :type="isLiked ? 'heart-filled' : 'heart'" size="24"
								:color="isLiked ? '#e63946' : '#999'"></uni-icons>
							<text class="like-count">{{ likeCount }}</text>
						</view>
						<view class="share-btn">
							<uni-icons type="share" size="24" color="#999"></uni-icons>
							<text class="share-text">分享</text>
						</view>
					</view>
				</view>

				<!-- 新闻内容（原生文本+图片） -->
				<view class="news-content">
				  <view class="content-text">
				    <template v-for="(block, index) in newsItem.contentBlocks" :key="index">
				      <!-- 文本块 -->
				      <text class="paragraph" v-if="block.type === 'text'">
				        {{ block.content }}
				      </text>
				      
				      <!-- 图片块 -->
				      <view class="content-image-item" v-if="block.type === 'image'">
				        <image 
				          :src="block.src" 
				          :alt="block.alt || '新闻图片'"
				          mode="widthFix" 
				          @error="handleImageError(index, 'content')"
				          @click="previewImage(block.src, newsItem.contentBlocks)"
				        ></image>
				      </view>
				    </template>
				  </view>
				</view>

				<!-- 点赞/评论统计 -->
				<view class="stats-bar">
					<view class="stats-item">
						<uni-icons type="heart" size="20" color="#e63946"></uni-icons>
						<text class="stats-text">{{ likeCount }} 人点赞</text>
					</view>
					<view class="stats-item">
						<uni-icons type="chatbubbles" size="20" color="#666"></uni-icons>
						<text class="stats-text">{{ newsItem.comments }} 条评论</text>
					</view>
				</view>

				<!-- 添加评论区 -->
				<view class="comment-input-bar">
					<input type="text" v-model="commentContent" placeholder="发表你的看法..." placeholder-style="color:#999">
					<button class="submit-btn" @click="submitComment" :disabled="!commentContent.trim()">
						发布
					</button>
				</view>

				<!-- 评论列表 -->
				<view class="comments-section" v-if="commentList.length > 0 || newsItem.comments !== '0'">
					<view class="section-title">
						<text class="title-text">精彩评论</text>
					</view>
					<view class="comment-list">
						<view class="comment-item" v-for="(comment, idx) in commentList" :key="idx">
							<view class="comment-avatar">
								<image src="/static/avatar/default.png" mode="aspectFill"></image>
							</view>
							<view class="comment-content">
								<view class="comment-header">
									<text class="comment-nickname">{{ comment.nickname }}</text>
									<text class="comment-time">{{ comment.time }}</text>
								</view>
								<view class="comment-text">{{ comment.content }}</view>
								<view class="comment-actions">
									<view class="comment-like" @click="likeComment(idx)">
										<uni-icons :type="comment.isLiked ? 'heart-filled' : 'heart'" size="18"
											:color="comment.isLiked ? '#e63946' : '#999'"></uni-icons>
										<text class="like-num">{{ comment.likeCount }}</text>
									</view>
									<view class="comment-reply">
										<uni-icons type="reply" size="18" color="#999"></uni-icons>
										<text class="reply-text">回复</text>
									</view>
								</view>
							</view>
						</view>
					</view>
					<view class="load-more-comments" v-if="showLoadMore">
						<text class="load-more-text" @click="loadMoreComments">加载更多评论</text>
					</view>
				</view>

				<!-- 精彩推荐 -->
				<view class="recommend-section">
					<view class="section-title">
						<text class="title-text">精彩推荐</text>
					</view>
					<view class="recommend-list">
						<view class="recommend-item" v-for="(item, idx) in recommendList" :key="idx"
							@click="navigateToDetail(item)">
							<view class="recommend-img">
								<image :src="item.imagelist[0] || '/static/newsimage/load_default.png'"
									mode="aspectFill"></image>
							</view>
							<view class="recommend-content">
								<text class="recommend-title">{{ item.title }}</text>
								<view class="recommend-footer">
									<text class="recommend-author">{{ item.author }}</text>
									<text class="recommend-comments">{{ item.comments }} 评</text>
								</view>
							</view>
						</view>
					</view>
				</view>
			</view>
		</scroll-view>
	</view>
</template>

<script>
	import newsData from "../../Data/news.json";

	export default {
		name: "newsDetail",
		data() {
			return {
				newsItem: {}, // 当前新闻详情
				isLiked: false, // 是否点赞当前新闻
				likeCount: 5114, // 新闻点赞数
				isFollowed: false, // 是否关注作者
				commentContent: "", // 新增评论内容
				commentList: [], // 评论列表
				showLoadMore: true, // 是否显示加载更多评论
				recommendList: [], // 推荐新闻列表
				currentCommentPage: 1, // 评论当前页码
				commentPageSize: 5, // 评论每页条数
				imageErrorList: [] // 图片加载错误记录
				
			};
		},
		onLoad(options) {
		  // 接收完整的新闻对象
		  this.newsItem = JSON.parse(decodeURIComponent(options.newsItem));
		  this.initRecommendList(this.newsItem.nID);
		  this.initCommentList();
		  // 补充作者头像（如果需要）
		  this.newsItem.authorAvatar = this.newsItem.authorAvatar || `/static/avatar/author_${this.newsItem.nID % 10}.png`;
		},
		methods: {
			formatContent(content) {
				if (!content) {
					// 若新闻没有content字段，显示默认提示
					return '<p>暂无详细内容，敬请期待...</p>';
				}
				// 把纯文本的 \n 转成 HTML 的 <br>，支持换行；已含HTML标签的内容不影响
				return content.replace(/\n/g, '<br>');
			},
			// 初始化新闻详情
			initNewsDetail(nID) {
				const newsList = newsData.newsList || [];
				this.newsItem = newsList.find(item => item.nID === nID) || {};
				this.newsItem.imagelist = this.newsItem.imagelist || []; 
				// 作者信息补充
				this.newsItem.authorId = this.newsItem.authorId || `author${nID}`;
				this.newsItem.authorAvatar = this.newsItem.authorAvatar || `/static/avatar/author_${nID % 10}.png`;
				// 模拟关注状态
				this.isFollowed = this.checkIfFollowed(this.newsItem.authorId);
				// 点赞数初始化
				this.likeCount = this.newsItem.comments ?
					Math.floor(parseFloat(this.newsItem.comments) * 0.3) + 10 :
					10;
			},

			// 初始化推荐列表（排除当前新闻）
			initRecommendList(currentNID) {
				const newsList = newsData.newsList || [];
				const sameCategory = newsList
					.filter(item => item.category === this.newsItem.category && item.nID !== currentNID)
					.slice(0, 2);
				const otherCategory = newsList
					.filter(item => item.nID !== currentNID && !sameCategory.some(s => s.nID === item.nID))
					.sort(() => Math.random() - 0.5)
					.slice(0, 3);
				this.recommendList = [...sameCategory, ...otherCategory];
			},

			// 初始化评论列表（模拟数据）
			initCommentList() {
				const commentCount = this.newsItem.comments ? parseFloat(this.newsItem.comments) : 0;
				const mockComments = [];
				const commentNum = Math.min(commentCount, this.commentPageSize);

				for (let i = 0; i < commentNum; i++) {
					mockComments.push({
						nickname: `用户${Math.floor(Math.random() * 10000)}`,
						content: this.getRandomComment(),
						time: this.getRandomCommentTime(),
						likeCount: Math.floor(Math.random() * 50),
						isLiked: false
					});
				}

				this.commentList = mockComments;
				this.showLoadMore = commentCount > this.commentPageSize;
			},

			// 加载更多评论
			loadMoreComments() {
				this.currentCommentPage++;
				const commentCount = this.newsItem.comments ? parseFloat(this.newsItem.comments) : 0;
				const remaining = commentCount - this.commentList.length;
				const loadNum = Math.min(remaining, this.commentPageSize);

				if (loadNum <= 0) {
					this.showLoadMore = false;
					return;
				}

				const newComments = [];
				for (let i = 0; i < loadNum; i++) {
					newComments.push({
						nickname: `用户${Math.floor(Math.random() * 10000)}`,
						content: this.getRandomComment(),
						time: this.getRandomCommentTime(),
						likeCount: Math.floor(Math.random() * 50),
						isLiked: false
					});
				}

				this.commentList = [...this.commentList, ...newComments];
				this.showLoadMore = this.commentList.length < commentCount;
			},

			// 切换新闻点赞状态
			toggleLike() {
				this.isLiked = !this.isLiked;
				this.likeCount += this.isLiked ? 1 : -1;
			},

			// 切换关注状态
			toggleFollow() {
				this.isFollowed = !this.isFollowed;
				// 实际项目中替换为接口请求
				const toastText = this.isFollowed ? '已关注' : '已取消关注';
				uni.showToast({
					title: toastText,
					icon: this.isFollowed ? 'success' : 'none'
				});
			},

			// 检查是否已关注作者
			checkIfFollowed(authorId) {
				const followedAuthors = ['author1', 'author3']; // 模拟已关注列表
				return followedAuthors.includes(authorId);
			},

			// 点击头像进入作者主页
			viewAuthorHome() {
				uni.navigateTo({
					url: `/pages/authorHome/authorHome?authorId=${this.newsItem.authorId}`
				});
			},

			// 评论点赞
			likeComment(idx) {
				const comment = this.commentList[idx];
				comment.isLiked = !comment.isLiked;
				comment.likeCount += comment.isLiked ? 1 : -1;
				this.$set(this.commentList, idx, comment);
			},

			// 提交评论
			submitComment() {
				const content = this.commentContent.trim();
				if (!content) return;

				const newComment = {
					nickname: "我",
					content: content,
					time: this.formatCommentTime(new Date()),
					likeCount: 0,
					isLiked: false
				};

				this.commentList.unshift(newComment);
				this.commentContent = "";

				const currentComments = parseFloat(this.newsItem.comments) || 0;
				this.newsItem.comments = (currentComments + 1) + (currentComments >= 1 ? "万" : "");
			},

			// 图片加载错误处理
			 handleImageError(index, type) {
			    if (type === 'content') {
			      this.$set(this.newsItem.contentBlocks[index], 'src', '/static/newsimage/load_fail.png');
			    } else {
			      this.$set(this.newsItem.imagelist, index, '/static/newsimage/load_fail.png');
			    }
			  },
			  
			  // 预览内容中的图片
			  previewImage(currentSrc, allBlocks) {
			    const urls = allBlocks
			      .filter(block => block.type === 'image')
			      .map(block => block.src);
			      
			    uni.previewImage({
			      urls,
			      current: currentSrc
			    });
			  },

			// 图片预览
			previewImage(idx) {
				const currentImg = this.newsItem.imagelist[idx];
				uni.previewImage({
					urls: this.newsItem.imagelist,
					current: currentImg
				});
			},

			// 跳转到其他新闻详情
			navigateToDetail(item) {
				uni.navigateTo({
					url: `/pages/newsDetail/newsDetail?nID=${item.nID}`
				});
			},

			// 返回上一页
			navigateBack() {
				uni.navigateBack({
					delta: 1
				});
			},

			// 格式化完整时间（年月日时分）
			formatFullTime(timeStr) {
				if (!timeStr) return "";
				const date = new Date(timeStr);
				if (isNaN(date.getTime())) return timeStr;
				return date.toLocaleString([], {
					year: "numeric",
					month: "2-digit",
					day: "2-digit",
					hour: "2-digit",
					minute: "2-digit",
					hour12: false
				});
			},

			// 格式化评论时间
			formatCommentTime(date) {
				const now = new Date();
				const diff = now - date;
				const minute = 60 * 1000;
				const hour = 60 * minute;
				const day = 24 * hour;

				if (diff < minute) return "刚刚";
				if (diff < hour) return `${Math.floor(diff / minute)}分钟前`;
				if (diff < day) return `${Math.floor(diff / hour)}小时前`;
				return date.toLocaleDateString([], {
					month: "2-digit",
					day: "2-digit"
				});
			},

			// 生成随机评论内容
			getRandomComment() {
				const comments = [
					"这个新闻太及时了，支持！",
					"感谢分享，学到了很多知识。",
					"对此你们怎么看？欢迎讨论。",
					"希望能有更多这样的深度报道！",
					"观点很独特，值得思考。",
					"为小编点赞，内容很精彩！",
					"期待后续发展，持续关注中。",
					"分析得很到位，支持作者！"
				];
				return comments[Math.floor(Math.random() * comments.length)];
			},

			// 生成随机评论时间
			getRandomCommentTime() {
				const now = new Date();
				const randomDays = Math.floor(Math.random() * 30);
				const randomHours = Math.floor(Math.random() * 24);
				const randomMinutes = Math.floor(Math.random() * 60);

				const commentTime = new Date(
					now.getTime() - (randomDays * 24 * 60 * 60 * 1000) - (randomHours * 60 * 60 * 1000) - (
						randomMinutes * 60 * 1000)
				);

				return this.formatCommentTime(commentTime);
			}
		}
	};
</script>

<style scoped>
	/* 顶部导航栏 */
	.top-nav {
		display: flex;
		align-items: center;
		justify-content: space-between;
		padding: 16rpx 20rpx;
		background-color: #fff;
		border-bottom: 1rpx solid #f5f5f5;
		position: sticky;
		top: 0;
		z-index: 999;
	}

	.nav-title {
		font-size: 32rpx;
		font-weight: bold;
		color: #333;
	}

	.empty-box {
		width: 28rpx;
	}

	/* 滚动容器 */
	.detail-scroll {
		width: 100%;
		min-height: calc(100vh - 88rpx);
		background-color: #f5f5f5;
	}

	/* 详情容器 */
	.detail-container {
		padding: 20rpx;
		background-color: #fff;
		margin-bottom: 15rpx;
	}

	/* 新闻标题 */
	.news-title {
		font-size: 36rpx;
		font-weight: bold;
		color: #333;
		margin-bottom: 20rpx;
		line-height: 1.5;
	}

	/* 作者信息栏 */
	.author-bar {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 25rpx;
		padding-bottom: 15rpx;
		border-bottom: 1rpx solid #f5f5f5;
	}

	.author-info {
		display: flex;
		align-items: center;
		gap: 12rpx;
	}

	.author-avatar-wrap {
		width: 60rpx;
		height: 60rpx;
		border-radius: 50%;
		overflow: hidden;
		flex-shrink: 0;
	}

	.author-avatar {
		width: 100%;
		height: 100%;
		object-fit: cover;
	}

	.author-text {
		display: flex;
		flex-direction: column;
	}

	.author-name {
		font-size: 26rpx;
		color: #333;
		font-weight: 500;
		margin-bottom: 4rpx;
	}

	.publish-time {
		font-size: 20rpx;
		color: #999;
	}

	/* 关注按钮 */
	.follow-btn {
		background-color: #e63946;
		color: #fff;
		font-size: 22rpx;
		padding: 6rpx 18rpx;
		border-radius: 20rpx;
		margin-right: 20rpx;
	}

	.follow-btn.followed {
		background-color: #f5f5f5;
		color: #666;
	}

	/* 点赞/分享区 */
	.like-share {
		display: flex;
		align-items: center;
		gap: 30rpx;
		margin-left: auto;
	}

	.like-btn,
	.share-btn {
		display: flex;
		flex-direction: column;
		align-items: center;
	}

	.like-count,
	.share-text {
		font-size: 20rpx;
		color: #999;
		margin-top: 4rpx;
	}

	/* 新闻内容 */
	.news-content {
		margin-bottom: 30rpx;
	}

	.content-text {
		font-size: 28rpx;
		color: #333;
		line-height: 1.8;
	}

	.paragraph {
		display: block;
		margin-bottom: 25rpx;
		text-align: justify;
	}

	.content-images {
		display: flex;
		flex-wrap: wrap;
		gap: 15rpx;
		margin: 25rpx 0;
	}
	.rich-content {
	  font-size: 28rpx;
	  color: #333;
	  line-height: 1.8;
	}
	
	.rich-content p {
	  margin-bottom: 25rpx;
	  text-align: justify;
	}
	
	.rich-content br {
	  margin-bottom: 15rpx;
	}

	.image-item {
		width: 31%;
		border-radius: 8rpx;
		overflow: hidden;
	}

	.image-item image {
		width: 100%;
		height: auto;
		object-fit: cover;
	}

	/* 统计栏 */
	.stats-bar {
		display: flex;
		justify-content: space-around;
		padding: 15rpx 0;
		border-top: 1rpx solid #f5f5f5;
		border-bottom: 1rpx solid #f5f5f5;
		margin-bottom: 30rpx;
	}

	.stats-item {
		display: flex;
		align-items: center;
		gap: 8rpx;
		color: #666;
		font-size: 24rpx;
	}

	.stats-text {
		font-size: 22rpx;
	}

	/* 评论输入框 */
	.comment-input-bar {
		display: flex;
		align-items: center;
		gap: 15rpx;
		padding: 15rpx;
		background-color: #f9f9f9;
		border-radius: 40rpx;
		margin-bottom: 30rpx;
	}

	.comment-input-bar input {
		flex: 1;
		height: 60rpx;
		font-size: 24rpx;
		background-color: transparent;
	}

	.submit-btn {
		background-color: #e63946;
		color: #fff;
		border-radius: 30rpx;
		padding: 0 30rpx;
		height: 60rpx;
		line-height: 60rpx;
		font-size: 24rpx;
	}

	.submit-btn:disabled {
		background-color: #ccc;
	}

	/* 评论区 */
	.comments-section {
		margin-bottom: 40rpx;
	}

	.section-title {
		margin-bottom: 20rpx;
		padding-bottom: 10rpx;
		border-bottom: 2rpx solid #e63946;
	}

	.title-text {
		font-size: 30rpx;
		font-weight: bold;
		color: #333;
	}

	.comment-list {
		margin-bottom: 20rpx;
	}

	.comment-item {
		display: flex;
		gap: 15rpx;
		padding: 15rpx 0;
		border-bottom: 1rpx solid #f5f5f5;
	}

	.comment-avatar {
		width: 60rpx;
		height: 60rpx;
		border-radius: 50%;
		overflow: hidden;
		flex-shrink: 0;
	}

	.comment-avatar image {
		width: 100%;
		height: 100%;
		object-fit: cover;
	}

	.comment-content {
		flex: 1;
	}

	.comment-header {
		display: flex;
		justify-content: space-between;
		margin-bottom: 8rpx;
	}

	.comment-nickname {
		font-size: 24rpx;
		font-weight: 500;
		color: #333;
	}

	.comment-time {
		font-size: 20rpx;
		color: #999;
	}

	.comment-text {
		font-size: 24rpx;
		color: #333;
		margin-bottom: 12rpx;
		line-height: 1.6;
	}

	.comment-actions {
		display: flex;
		gap: 30rpx;
	}

	.comment-like,
	.comment-reply {
		display: flex;
		align-items: center;
		gap: 6rpx;
		font-size: 20rpx;
		color: #999;
	}

	.like-num,
	.reply-text {
		font-size: 18rpx;
	}

	.load-more-comments {
		display: flex;
		justify-content: center;
		padding: 15rpx 0;
	}

	.load-more-text {
		font-size: 24rpx;
		color: #e63946;
	}

	/* 推荐区 */
	.recommend-section {
		margin-bottom: 20rpx;
	}

	.recommend-list {
		display: flex;
		flex-direction: column;
		gap: 15rpx;
	}

	.recommend-item {
		display: flex;
		gap: 15rpx;
		padding: 10rpx 0;
		border-bottom: 1rpx solid #f5f5f5;
	}

	.recommend-img {
		width: 140rpx;
		height: 100rpx;
		border-radius: 8rpx;
		overflow: hidden;
		flex-shrink: 0;
	}

	.recommend-img image {
		width: 100%;
		height: 100%;
		object-fit: cover;
	}

	.recommend-content {
		flex: 1;
		display: flex;
		flex-direction: column;
		justify-content: space-between;
	}

	.recommend-title {
		font-size: 24rpx;
		color: #333;
		line-height: 1.5;
		display: -webkit-box;
		-webkit-line-clamp: 2;
		-webkit-box-orient: vertical;
		overflow: hidden;
		margin-bottom: 8rpx;
	}

	.recommend-footer {
		display: flex;
		justify-content: space-between;
		font-size: 20rpx;
		color: #999;
	}
	.content-text {
	  font-size: 28rpx;
	  color: #333;
	  line-height: 1.8;
	}
	
	.paragraph {
	  display: block;
	  margin-bottom: 25rpx;
	  text-align: justify;
	}
	
	.content-image-item {
	  margin: 25rpx 0; /* 图片与上下文本的间距 */
	  border-radius: 8rpx;
	  overflow: hidden;
	}
	
	.content-image-item image {
	  width: 100%;
	  height: auto;
	  object-fit: cover;
	}
</style>